import time

from xtquant.xttrader import XtQuantTrader
from xtquant.xttype import StockAccount

# 定义QMT客户端路径（需要根据实际安装路径修改）
QMT_PATH = r"C:\Tools\QMT\userdata_mini"


def get_account_positions():
    """
    获取指定证券账号的持仓信息

    Returns:
    pd.DataFrame: 持仓信息DataFrame
    """
    session_id = int(time.time())
    # 创建交易对象（需要提供路径和会话ID）
    trader = XtQuantTrader(QMT_PATH, session_id)
    # 启动交易对象
    trader.start()
    # 连接账户
    connect_result = trader.connect()
    print('建立交易连接，返回0表示连接成功: ', connect_result)

    # 创建账号对象
    acc = StockAccount('11510147')
    account_info = trader.query_stock_asset(acc)
    available_cash = account_info.m_dCash
    print(acc.account_id, '可用资金', available_cash)
    # 获取持仓信息
    positions = trader.query_stock_positions(acc)
    position_total_dict = {i.stock_code: i.m_nVolume for i in positions}
    print(acc.account_id, '持仓字典', position_total_dict)

    acc1 = StockAccount('211510147', 'CREDIT')
    positions1 = trader.query_stock_positions(acc1)
    position_total_dict1 = {i.stock_code: i.m_nVolume for i in positions1}
    print(acc1.account_id, '持仓字典', position_total_dict1)


if __name__ == "__main__":
    print("正在获取账户持仓信息...")
    get_account_positions()
